# 3.7 Ultrasonic Sensor ## 3.7.1 Overview Ultrasonic sensor measures the distance of an object by sound waves. It boasts a transmitter and a receiver to emit sound waves and then measure the returned waves. The time difference between transmitting and receiving can be used to calculate the distance value. Beyond that, it is also used to detect the shape or presence of objects, build automatic doors, and measure flow rates and pressures. ## 3.7.2 Schematic Diagram ![t85](./media/t85.png) **Working principle:** Like bats, the ultrasonic sensor sends an ultrasonic signal with a high frequency that human cannot hear. If these signals encounter obstacles, they will immediately reflect back and be received by the sensor. After that, the distance between the sensor and the obstacle is calculated according to the time difference between signals transmitting and receiving. **Maximum detection distance:** 3M **Minimum detection distance:** 4cm **Detection angle:** no greater than 15 degrees ## 3.7.3 Code Blocks Blocks in ![](./media/codingBox.png): 1. ![t86](./media/t86.png) is a block included in coding box library. It reads the distance values detected by the ultrasonic sensor in the coding box. ## 3.7.4 Test Code You can manually build blocks, or directly open the code file we provide: `3-7-Ultrasonic.ubp`. If you have any questions about how to open code files or upload code, please back to `1.9 Upload Code`. **Build code blocks:** 1. In ![](./media/control.png), drag ![](./media/t1.png) and ![](./media/t2.png) to the script area, and stack them together. ![t34](./media/t34.png) 2. In ![](./media/output.png), drag ![t44](./media/t44.png) block and put it in ![](./media/t2.png). 3. Tap ![t47](./media/t47.png) of the ![t44](./media/t44.png) to add an output blank. In the first blank, enter `distance:` ![t87](./media/t87.png) 4. In ![](./media/codingBox.png), drag ![t86](./media/t86.png) and place it in the second blank of ![t87](./media/t87.png). 5. In ![](./media/control.png), drag ![t4](./media/t4.png) and put it under ![t87](./media/t87.png), and modify the delay to `100ms`. **Complete code:** ![t88](./media/t88.png) ## 3.7.5 Test Result Connect the coding box to the MicroBlocks via USB or Bluetooth, and click ![t59](./media/t59.png) to upload the code to the coding box. If you wave you hand in front of the ultrasonic sensor or move back and forth, you can see the change in the printed distance values. ![t89](./media/t89.png)